import React, {useEffect, useState, } from 'react'
import {Card, Table, Button, Popconfirm, message} from 'antd'
import {useNavigate} from "react-router-dom";
import {deleteOne, listApi} from "../../services/products";
import './List.css'

function List() {
    const navigate = useNavigate();
    const [dataSource, setDataSource] = useState([]); // 使用状态管理数据
    const [loading, setLoading] = useState(false); // 添加加载状态
    const [currentPage, setCurrentPage] = useState(1); // 当前页码
    const [totalRecords, setTotalRecords] = useState(0)
    // 通过listApi获取数据
    useEffect(() => {
       fetchData(currentPage);


    },[currentPage]) // 监听 currentPage 变化

    const fetchData = async (page)=>{

        setLoading(true);
        try {
            const response = await listApi(page); // 获取第1页数据
            console.log('获取商品列表成功:', response);

            // 根据你的后端返回格式处理数据
            // 注意：这里直接使用 response，因为 request.js 的拦截器已经处理了 code 判断
            if (response && response.products) {
                // 从 response.products 中获取商品数据
                const products = response.products;

                // 为每个数据项添加 key 属性
                const dataWithKeys = products.map(item => ({
                    ...item,
                    key: item._id,  // 使用 _id 作为 key
                    id: item._id    // 添加 id 字段以匹配表格列
                }));

                setDataSource(dataWithKeys);
                setTotalRecords(response.totalCount);
            } else {
                message.error('数据格式不正确');
            }
        } catch (error) {
            console.error('获取商品列表失败:', error);
            message.error('获取数据失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    }

    // 添加分页变化
    const handleTableChange = (pagination) => {
        setCurrentPage(pagination.current); // 更新当前页码
    };
    // 页面减一
    const handlePrevPage= ()=>{
        if(currentPage>1){
            setCurrentPage(currentPage-1)
        }
    }
    // 页面加一
    const handleNextPage=()=>{
        setCurrentPage(currentPage+1)
    }

    // 删除商品
    const handleDelete = async(id,name)=>{
        try{
            setLoading(true);
            const response = await deleteOne(id);
            if(response){
                message.success(`商品"${name}"删除成功`);
                // 重新获取数据
                fetchData(currentPage);
            }else{
                message.error(`商品"${name}"删除失败`);
            }

        }catch (error){
            console.error('删除商品失败:', error);
            message.error(`商品"${name}"删除失败: ${error.message}`);
        } finally {
            setLoading(false)
        }
    }

    const columns = [
        {
            title: '序号',
            dataIndex: "id",
            width: 80,
            align: "center",
            render: (text, record, index) => (<span>{index + 1}</span>)
        },
        {
            title: '商品名称',
            dataIndex: "name"
        },
        {
            title: '图片',
            dataIndex: 'coverImg',
            key: 'coverImg',
            render: (text) => (
                <div>
                    {text ? (
                        <img
                            src={text}
                            alt="商品图片"
                            style={{ width: '80px', height: '80px', objectFit: 'cover' }}
                        />
                    ) : (
                        <span>无图片</span>
                    )}
                </div>
            )

        },
        {
            title: '价格',
            dataIndex: "price",
            render: (text) => (
                <span>${text.toFixed(2)}</span>
            )
        },
        {
            title: '库存',
            dataIndex: "stock"
        },
        {
            // 添加修改操作
            title: '操作',
            render: (text, record, index) => {
                return (
                    <div>
                        <Button
                            type="primary"
                            size="small"
                            onClick={()=>navigate(`/admin/products/edit/${record.id}`)}
                        >
                            修改
                        </Button>
                        {/* 添加删除提示 */}
                        <Popconfirm
                            title="确定删除此项？"
                            description={`确定要删除商品"${record.name}"吗？`}
                            onCancel={() => console.log('用户取消删除')}
                            onConfirm={() => {
                                console.log("用户确认删除，商品ID:", record.id)
                                // 后面需要调用API接口 - deleteOne
                                handleDelete(record.id, record.name);
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                        <Button
                            style={{marginLeft: "1rem"}}
                            type="primary"
                            size="small"
                            danger
                        >
                            删除
                        </Button>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ]

    return (
        <Card
            title="商品列表"
            extra={<Button type="primary" size="small" onClick={()=>navigate('/admin/products/edit/new')}>新增</Button>}
        >
            <Table
                columns={columns}
                bordered
                dataSource={dataSource}
                loading={loading}
                pagination={
                    false
                }

                onChange={handleTableChange}
            />
            {/* 添加分页控制按钮 */}
            {/* 自定义分页控制按钮 */}
            <div className="pagination-container">
                <Button
                    onClick={handlePrevPage}
                    disabled={currentPage === 1}
                    className="pagination-button"
                >
                    {/*// >*/}
                    &lt;
                </Button>
                <span className="pagination-current-page">{currentPage}</span>
                <Button
                    onClick={handleNextPage}
                    disabled={currentPage >= Math.ceil(totalRecords / 10)}
                    className="pagination-button"
                >
                    {/*// <*/}
                    &gt;
                </Button>
            </div>
        </Card>
    )
}

export default List
